﻿using System;
using System.Collections.Generic;
using System.Text;
using Cn.Cellula.Biz.Port;
using Cn.Cellula.Model;
using System.Reflection;
using Cn.Edwon.Spring;
using System.Xml;
using Cn.Cellula.Model.Product;
using Cn.Cellula.Model.Content;
using Cn.Cellula.Model.System;
using Cn.Edwon.Web.Script;

namespace Cn.Cellula.Biz.Impl {
    class ProductBiz : MyBizSupport, IProductBiz {
        public String GenerateProductNo() { 
            //前6位
            IList<VProductNoMaxEO> list = base.LoadAll<VProductNoMaxEO>();
            if (list != null && list.Count == 1) {
                Int32 no = Convert.ToInt32(list[0].ProductNo);
                return (no + 1) + "";
            } else {
                String y = (DateTime.Now.Year - 2000) + "";
                String m = (DateTime.Now.Month < 10) ? ("0" + DateTime.Now.Month) : DateTime.Now.Month+"";
                String d = (DateTime.Now.Day < 10) ? ("0" + DateTime.Now.Day) : DateTime.Now.Day + "";
                return y + m + d + "0001";
            }
        }

        #region IProductBiz 成员

        public IList<TProductPicEO> LoadPicByProduct(string rProductKey) {
            String hql = " from TProductPicEO eo where eo.ProductId='" + rProductKey + "' ";
            return base.Find<TProductPicEO>(hql);
        }

        
        public IList<TProductInMarketEO> LoadProductMarket(string rProductKey) {
            String hql = " from TProductInMarketEO eo where eo.ProductKey='" + rProductKey + "'";
            return base.Find<TProductInMarketEO>(hql);
        }

        public void UpdateProductMarket(string rOwnerKey,string rProductKey, string[] rMarketKeys) {
            String hql = "from TProductEO eo where eo.ProductId='" + rProductKey + "' and eo.OwnerKey='"+rOwnerKey+"'";
            IList<TProductEO> list = base.Find<TProductEO>(hql);
            if (list != null && list.Count > 0) {
                hql = " from TProductInMarketEO eo where eo.ProductKey='" + rProductKey + "'";
                base.Delete(hql);

                foreach (String s in rMarketKeys) {
                    TProductInMarketEO eo = new TProductInMarketEO();
                    eo.MarketKey = s;
                    eo.ProductKey = rProductKey;
                    base.Save<TProductInMarketEO>(eo);
                }
            } else {
                log.Error("视图修改不同ownerkey的产品数据");
                throw new Exception("权限错误");
            }
        }

        public bool IfProductNoExist(string rProductNo) {
            String hql = "from TProductEO eo where eo.ProductNo='" + rProductNo + "'";
            IList<TProductEO> list = base.Find<TProductEO>(hql);
            return (list != null && list.Count > 0);
        }

        public void DeleteProduct(IList<String> rKeys) {
            foreach (String s in rKeys) {
                TProductEO eo = base.Load<TProductEO>(s);
                //设置删除标记
                eo.FlgDel = 1;
                //被删除的商品将无分类
                //eo.CategoryId = "";
                base.Update<TProductEO>(eo);

                //删除文件关联

                //删除商铺关联
                try {
                    String hql = "from TProductInMarket eo where eo.ProductKey='" + eo.ProductId + "'";
                    base.Delete(hql);
                } catch (Exception ex) {
                    log.Error("删除商品-删除其所属店铺关联时出现异常:" + ex.Message);
                }

                //删除模板属性关联
                try {
                    String hql = "from TProductAtlDataEO eo where eo.ProductKey='" + eo.ProductId + "'";
                    base.Delete(hql);
                } catch (Exception ex) {
                    log.Error("删除商品-删除其模板属性值时出现异常:" + ex.Message);
                }

            }
        }


        public void BindProductInGroup(IList<string> rProductKeys, string rGroupKey) {
            try {
                foreach (String s in rProductKeys) {
                    TProductInGroupEO eo = new TProductInGroupEO();
                    eo.GroupKey = rGroupKey;
                    eo.ProductKey = s;
                    base.Save<TProductInGroupEO>(eo);
                }
            } catch(Exception ex) {
                log.Error(ex.Message);
            }
        }

        public void BindProductOutGroup(IList<string> rProductKeys, string rGroupKey) {
            try {
                String keys = "0";
                foreach (String s in rProductKeys) {
                    keys += ",'" + s + "'";
                }
                String hql = "from TProductInGroupEO eo where eo.ProductKey in (" + keys + ") and eo.GroupKey='" + rGroupKey + "'";
                base.Delete(hql);
            } catch (Exception ex) {
                log.Error(ex.Message);
            }
        }



        public IList<VProductInMarketEO> LoadMarketByProduct(String rProductKey) {
            String hql = "from VProductInMarketEO eo where eo.ProductKey='" + rProductKey + "'";
            IList<VProductInMarketEO> list = base.Find<VProductInMarketEO>(hql);
            ICategoryBiz cbiz = BizFactory.Get<ICategoryBiz>();
            XmlDocument doc = cbiz.LoadCatalog2XHtml(null, CodeTypeDef.Category.Market, null);
            XmlElement root = doc.DocumentElement;
            foreach (VProductInMarketEO eo in list) {
                IList<TSysCategoryEO> cl = cbiz.LoadCategoryPath(doc, eo.MarketKey);
                if (cl != null && cl.Count > 0) {
                    eo.MarketName = "";
                    for (int i=0;i<cl.Count;i++){
                        TSysCategoryEO c = cl[i];
                        if (i == 0)
                            eo.MarketName = c.CategoryName;
                        else
                            eo.MarketName = c.CategoryName + "," + eo.MarketName;
                    }
                }
            }
            return list;
        }



        public string LoadProductDetails2Json(string rKey) {
            VProductDetailsEO product = null;
            try {
                product = base.Load<VProductDetailsEO>(rKey);
            } catch (Exception ex) {
                log.Error(ex.Message);
                return "[]";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"EO\":" + JsUtil.ParseEO2Json(product));
            
            //商品所属的卖场
            sb.Append(",\"Market\":[");
            IList<VProductInMarketEO> list = LoadMarketByProduct(product.ProductId);
            for (int i = 0; i < list.Count; i++) {
                VProductInMarketEO eo = list[i];
                if (i > 0) {
                    sb.Append(",");
                }
                sb.Append("{\"Key\":\"" + eo.MarketKey + "\",\"Name\":\"" + eo.MarketName + "\"}");
            }
            sb.Append("]");
            
            //产品图片
            sb.Append(",\"Pic\":[");
            IList<TUploadFileEO> flist = BizFactory.Get<IUploadFileBiz>().LoadByModelKey(product.ProductId);
            for (int i = 0; i < flist.Count; i++) {
                TUploadFileEO eo = flist[i];
                if (i > 0) {
                    sb.Append(",");
                }
                sb.Append("{\"Path\":\"" + eo.FilePath + "\",\"Nail\":\"" + eo.Thumbnail + "\"}");
            }
            sb.Append("]");
            
            //产品扩展属性
            sb.Append(",\"Atl\":[");
            String hql = "from VProductAtlDataEO eo where eo.ProductKey='"+product.ProductId+"' ";
            IList<VProductAtlDataEO> atlList = this.Find<VProductAtlDataEO>(hql);
            if (atlList != null && atlList.Count > 0) {
                for (int i = 0; i < atlList.Count; i++) {
                    VProductAtlDataEO eo = atlList[i];
                    if (i > 0) {
                        sb.Append(",");
                    }
                    sb.Append("{\"Name\":\"" + eo.AtlName + "\",\"Value\":\"" + eo.DataValue + "\"}");
                }
            }
            sb.Append("]");

            sb.Append("}");
            return sb.ToString();
        }

        #endregion

        #region IProductBiz 成员


        public void SetList(IList<string> rKeys) {
            foreach (String s in rKeys) {
                TProductEO eo = base.Load<TProductEO>(s);
                eo.ListDate = DateTime.Now;
                eo.DelistDate = null;
                base.Update<TProductEO>(eo);
            }
        }

        public void SetDelist(IList<string> rKeys) {
            foreach (String s in rKeys) {
                TProductEO eo = base.Load<TProductEO>(s);
                eo.DelistDate = DateTime.Now;
                base.Update<TProductEO>(eo);
            }
        }


        public IList<TProductAtlOptionsEO> LoadAltOptions(string rAtlKey) {
            String hql = "from TProductAtlOptionsEO eo where eo.AtlKey='" + rAtlKey + "' order by eo.OrderNumber desc";
            return base.Find<TProductAtlOptionsEO>(hql);
        }

        #endregion

        #region IProductBiz 成员


        public void DeleteAlt(IList<string> rAltKeys) {
            foreach (String s in rAltKeys) {
                try {
                    String hql = "from TProductAtlOptionsEO eo where eo.AtlKey='" + s + "'";
                    base.Delete(hql);
                    base.Delete<TProductAtlEO>(s);
                } catch { }
            }
        }

        public void DeleteAltOption(IList<string> rOptKeys) {
            foreach (String s in rOptKeys) {
                try {
                    base.Delete<TProductAtlOptionsEO>(s);
                } catch { }
            }
        }

        public IList<VProductAtlEO> LoadProductAtlByCategory(string rCategoryKey) {
            String hql = "from VProductAtlEO eo ";
            hql += " where eo.CategoryKey='" + rCategoryKey + "' or eo.CategoryKey is null or eo.CategoryKey='' ";
            ICategoryBiz biz = BizFactory.Get<ICategoryBiz>();
            IList<TSysCategoryEO> ckeys = biz.LoadCategoryPath(null, CodeTypeDef.Category.Product, rCategoryKey);
            if (ckeys != null && ckeys.Count > 0) {
                for (int i = 0; i < ckeys.Count; i++) {
                    TSysCategoryEO k = ckeys[i];
                    hql += " or eo.CategoryKey='" + k.CategoryId + "' ";
                }
            }
            hql += " order by eo.CategoryKey,eo.OrderNumber desc ";
            return base.Find<VProductAtlEO>(hql);
        }
        public IList<VProductAtlOptionsEO> LoadProductOptByCategory(string rCategoryKey) {
            String hql = "from VProductAtlOptionsEO eo ";
            hql += " where eo.CategoryKey='" + rCategoryKey + "' or eo.CategoryKey is null or eo.CategoryKey='' ";
            ICategoryBiz biz = BizFactory.Get<ICategoryBiz>();
            IList<TSysCategoryEO> ckeys = biz.LoadCategoryPath(null, CodeTypeDef.Category.Product, rCategoryKey);
            if (ckeys != null && ckeys.Count > 0) {
                for (int i = 0; i < ckeys.Count; i++) {
                    TSysCategoryEO k = ckeys[i];
                    hql += " or eo.CategoryKey='" + k.CategoryId + "' ";
                }
            }
            hql += " order by eo.CategoryKey,eo.OrderNumber desc ";
            return base.Find<VProductAtlOptionsEO>(hql);
        }

        public void SaveProductAtlData(IList<TProductAtlDataEO> rDataList) {
            if (rDataList == null || rDataList.Count < 1) return;
            String productKey = rDataList[0].ProductKey;
            String hql = " from TProductAtlDataEO eo where eo.ProductKey='"+productKey+"' ";
            base.Delete(hql);
            foreach (TProductAtlDataEO eo in rDataList) {
                base.Save<TProductAtlDataEO>(eo);
            }
        }


        #endregion
    }
}
